<template>
    <div class="upload-container">
      <!-- 文件上传区域 -->
      <div class="upload-area" @click="triggerFileInput" @dragover.prevent @drop.prevent="handleDrop">
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          @change="handleFileChange"
          accept="image/*,video/*"
        />
        <div class="upload-content">
          <el-icon><Upload /></el-icon>
          <p>点击或拖拽文件到此处上传</p>
        </div>
      </div>
  
      <!-- 文件预览区域 -->
      <div class="preview-container" v-if="fileList.length > 0">
        <div v-for="(file, index) in fileList" :key="index" class="preview-item">
          <!-- 图片预览 -->
          <img v-if="isImage(file.url)" :src="file.url" class="preview-image" />
          <!-- 视频预览 -->
          <video v-else-if="isVideo(file.url)" :src="file.url" controls class="preview-video"></video>
          
          <div class="preview-actions">
            <el-button type="primary" size="small" @click="downloadFile(file)">下载</el-button>
            <el-button type="danger" size="small" @click="deleteFile(file)">删除</el-button>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Upload } from '@element-plus/icons-vue'
  import axios from 'axios'
  
  const fileInput = ref(null)
  const fileList = ref([])
  
  // 触发文件选择
  const triggerFileInput = () => {
    fileInput.value.click()
  }
  
  // 处理文件选择
  const handleFileChange = async (event) => {
    const file = event.target.files[0]
    if (file) {
      await uploadFile(file)
    }
  }
  
  // 处理拖拽上传
  const handleDrop = async (event) => {
    const file = event.dataTransfer.files[0]
    if (file) {
      await uploadFile(file)
    }
  }
  
  // 上传文件
  const uploadFile = async (file) => {
    try {
      const formData = new FormData()
      formData.append('file', file)
  
      const response = await axios.post('/api/oss/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
  
      if (response.data === '上传成功') {
        // 获取文件URL
        const urlResponse = await axios.get(`/api/oss/url?fileName=${file.name}`)
        fileList.value.push({
          name: file.name,
          url: urlResponse.data
        })
        ElMessage.success('上传成功')
      } else {
        ElMessage.error('上传失败')
      }
    } catch (error) {
      console.error('上传错误:', error)
      ElMessage.error('上传失败')
    }
  }
  
  // 下载文件
  const downloadFile = async (file) => {
    try {
      const response = await axios.get(`/oss/download?fileName=${file.name}`, {
        responseType: 'blob'
      })
      
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', file.name)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } catch (error) {
      console.error('下载错误:', error)
      ElMessage.error('下载失败')
    }
  }
  
  // 删除文件
  const deleteFile = async (file) => {
    try {
      await axios.delete(`/oss/?fileName=${file.name}`)
      fileList.value = fileList.value.filter(f => f.name !== file.name)
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除错误:', error)
      ElMessage.error('删除失败')
    }
  }
  
  // 判断是否为图片
  const isImage = (url) => {
    return /\.(jpg|jpeg|png|gif|webp)$/i.test(url)
  }
  
  // 判断是否为视频
  const isVideo = (url) => {
    return /\.(mp4|webm|ogg)$/i.test(url)
  }
  </script>
  
  <style scoped>
  .upload-container {
    padding: 20px;
  }
  
  .upload-area {
    border: 2px dashed #dcdfe6;
    border-radius: 6px;
    padding: 20px;
    text-align: center;
    cursor: pointer;
    transition: border-color 0.3s;
  }
  
  .upload-area:hover {
    border-color: #409eff;
  }
  
  .upload-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
  
  .preview-container {
    margin-top: 20px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
  }
  
  .preview-item {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
  }
  
  .preview-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
    border-radius: 4px;
  }
  
  .preview-video {
    width: 100%;
    max-height: 200px;
    border-radius: 4px;
  }
  
  .preview-actions {
    margin-top: 10px;
    display: flex;
    gap: 10px;
    justify-content: center;
  }
  </style>